import pymongo
from matplotlib import pylab as plt
from datetime import date, timedelta

## 精确使用pymongo

client = pymongo.MongoClient()
ganjix = client["ganjix"]
sample = ganjix["sample"]


## find函数控制的参数
# for i in sample.find({"pub_date":"2016.01.14"},{"area":{"$slice":1}, "_id":0, "price":0}).limit(100):
#     print(i)

## 查找时间段
## 使用find和update函数整理时间的数据
# for i  in sample.find():
#     frags = i["pub_date"].split("-")
#     if len(frags) == 1:
#         date = frags[0]
#     else:
#         date="{}.{}.{}".format(frags[0],frags[1],frags[2])
#     sample.update({"_id":i["_id"]},{"$set":{"pub_date":date}})

# for i  in sample.find():
#     frags = i["pub_date"].split("-")
#     if len(frags) == 1:
#         date = frags[0]
#     else:
#         date="{}.{}.{}".format(frags[0],frags[1],frags[2])
#     print(date)

def get_all_dates(date1, date2):
    the_date = date(int(date1.split(".")[0]),int(date1.split(".")[1]),int(date1.split(".")[2]))
    end_date = date(int(date2.split(".")[0]),int(date2.split(".")[1]),int(date2.split(".")[2]))
    days = timedelta(days =1)
    while the_date <= end_date:
        yield (the_date.strftime("%Y.%m.%d"))
        the_date = the_date + days

# for i in get_all_dates("2015.12.24","2016.01.15"):
#     print(i)

def get_data_within(date1, date2, areas):
    for area in areas:
        for date in get_all_dates(date1,date2):
            a = list(sample.find({"pub_date":date, "area":area}))
            print("#"*20, date, area, len(a), "#"*20)

## 获得各个地区的集合
area_list =[]
for i in sample.find():
    area_list.append(i["area"][0])
areas = list(set(area_list))


get_data_within("2015.12.24","2016.01.15", areas)